<template>
  <view :class="s.index">
    <view :class="s.loginContent">
      <AtInput
        clear
        required
        :error="usernameErr"
        v-model:value="userName"
        :border="false"
        title="用户名"
        placeholder="请输入用户名"
        type="text"
      />
      <AtInput
        clear
        required
        v-model:value="password"
        name="value3"
        title="密码"
        type="password"
        :border="false"
        placeholder="请输入密码"
        :error="passwordErr"
      />
    </view>

    <at-button type="primary" :loading="loading" @tap="startLogin"
      >登陆</at-button
    >
    <view :class="s.register" @tap="goRegister">没有账号？去注册一个吧</view>
    <view :class="s.errToast"><text>{{text}}</text></view>
  </view>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
import Taro from '@tarojs/taro'
import { AtInput,AtButton,AtToast } from "taro-ui-vue3";
import jwt from "./util/index.js"
interface login {
  userName: string;
  password: string;
}

export default defineComponent({
  components: {
    AtInput,
    AtButton,
    AtToast,
  },
  setup() {
    let text = ref<string>("");
    let err = reactive({
      usernameErr: false,
      passwordErr: false,
    });
    let loading = ref<boolean>(false)
    let login = reactive<login>({
      userName: "",
      password: "",
    });
    function change(value) {
      login.userName = value;
    }
    function goRegister():void{
      Taro.redirectTo({
        url:"/pages/register/register"
      })
    }
    async function startLogin():Promise<void> {
      loading.value = true
      if(login.userName&&login.password){
        err.passwordErr = false
        err.usernameErr = false
      let data = await Taro.request({
          url:"https://www.ttzxh.icu:443/api/user/login",
          method:"POST",
          data:{
            username:login.userName,
            password:login.password
          }
        })
      if(data.data.error===-1){
        let userInfo = jwt(data.data.data.token);
        Taro.setStorageSync("userInfo",userInfo)
        Taro.setStorageSync("token",data.data.data.token)
        Taro.reLaunch({
          url:"/pages/chat/index"
        })
      }else{
        text.value="用户名或密码错误"
        err.passwordErr = true
        err.usernameErr = true
      }
      }else {
        text.value="请输入用户名或密码"
      }
      loading.value = false
    }
    return {
      ...toRefs(login),
      ...toRefs(err),
      text,
      loading,
      change,
      startLogin,
      goRegister
    };
  },
});
</script>

<style lang="scss" module="s">
.index {
  width: 750rpx;
  height: 100vh;
  .loginContent {
    margin-bottom: 8px;
  }
  .register{
    padding: 8Px 16Px;
    color: #78A4FA;
    font-size: 12Px;
    text-align: right;
  }
  .errToast{
    color: red;
    text-align: center;
    font-size: 15Px;
  }
}
</style>